#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <qfiledialog.h>

#include <QList>
#include <QtNetwork/QNetworkInterface>

using namespace  std;

/**
 * @brief MainWindow::MainWindow
 * @param parent
 * Constructor to MainWindow class, in which launch some procedures.
 */
MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow),
  proc(NULL),
  fastrun(false)
{
  ui->setupUi(this);
  loadSettings();
}

/**
 * @brief MainWindow::~MainWindow
 * This destructor free resources used in previews activities.
 * Furthermore, stop the service if the user close the window before push
 * the StopButton.
 */
MainWindow::~MainWindow()
{
  saveSettings();
  delete ui;
  if (proc != NULL) delete proc;
}

/**
 * @brief MainWindow::loadSettings
 * This method recover the previews values, saved in the past execution.
 * All settings are safe in a ".python-httpserver-frontend.cfg" hidden file.
 */
void MainWindow::loadSettings()
{
  home = QDir::currentPath();
  QStringList args = QCoreApplication::arguments();
  if (args.count()==2) {
    if (QDir::setCurrent(args.at(1).trimmed()) ) {
      ui->pushButton_folder->setText( args.at(1).trimmed() );
      fastrun = true;
      on_pushButton_start_clicked();
      return;
    }
  }
  QFile f(home+"/.python-httpserver-frontend.cfg");
  f.open(QIODevice::ReadOnly);
  if (!f.isOpen()) {
     idiom.setIdiomType(ENG);
     ui->pushButton_folder->setText("~/");
     ui->lineEdit_port->setText("8000");
  }
  else {
    QString data1 = f.readLine().data();
    idiom.setIdiomType(data1=="eng\n"?ENG:SPA);
    QString data2 = f.readLine().data();
    ui->pushButton_folder->setText(data2.trimmed());
    QString data3 = f.readLine().data();
    ui->lineEdit_port->setText(data3.trimmed());
    refreshIdiom();
    QDir::setCurrent(ui->pushButton_folder->text());
    f.close();
  }
}

/**
 * @brief MainWindow::saveSettings
 * This method save the configurations in the ".python-httpserver-frontend.cfg"
 * file to be recover in the next execution.
 */
void MainWindow::saveSettings() {
  if (fastrun) return;
  QFile f(home+"/.python-httpserver-frontend.cfg");
  f.open(QIODevice::WriteOnly);
  if (!f.isOpen()) return;
  f.write( idiom.getIdiomType()==ENG?"eng\n":"spa\n" );
  f.write( (ui->pushButton_folder->text().toStdString()+"\n").c_str() );
  f.write( (ui->lineEdit_port->text().toStdString()+"\n").c_str() );
  f.close();
}

/**
 * @brief MainWindow::refreshIdiom
 * This method set the all labe objects in the interface with the new language
 * values. (english values or spanish values).
 */
void MainWindow::refreshIdiom() {
  setWindowTitle(idiom.getWindowTitle());
  ui->tabWidget->setTabText(0,idiom.getServer());
  ui->pushButton_start->setText(idiom.getStart());
  ui->pushButton_clear->setText(idiom.getClear());
  ui->tabWidget->setTabText(1,idiom.getSettings());
  ui->label_port->setText(idiom.getPort());
  ui->label_language->setText(idiom.getIdiom());
  ui->tabWidget->setTabText(2,idiom.getAbout());
  ui->comboBox_language->setCurrentIndex(idiom.getIdiomType()==ENG?0:1);
}

/**
 * @brief MainWindow::on_pushButton_start_clicked
 * This methos is a signal used to interface to code the instrucctions to be
 * executed when an user activate a Start/Stop Button.
 * This methos has two different codes: one to when button has a label "Start"
 * and another to when button has a labes "Stop".
 */
void MainWindow::on_pushButton_start_clicked()
{
  if (ui->pushButton_start->text().compare(idiom.getStart())==0) {
    proc = new QProcess;
    QString program = "python3";
    QStringList arguments;
    arguments << "-m" << "http.server"
              << ui->lineEdit_port->text().toStdString().c_str();
    proc->start(program,arguments);
    ui->pushButton_start->setText(idiom.getStop());
    ui->pushButton_folder->setEnabled(false);
    ui->tab_settings->setEnabled(false);

    QList<QHostAddress> list = QNetworkInterface::allAddresses();

    for(int nIter=0; nIter<list.count(); nIter++) {
      if(!list[nIter].isLoopback()) {
        if (list[nIter].protocol() == QAbstractSocket::IPv4Protocol ) {
          QString ip = list[nIter].toString();
          history += "<font color=green>"+idiom.getStarted()+"</font>";
          history += " "+idiom.getFindme()+"<br>";
          history += "<font color=blue>http://"+ip+":";
          history += ui->lineEdit_port->text()+"</font><br>";
          ui->textBrowser_history->setHtml(history);
        }
      }
    }

  }
  else {
    proc->close();
    delete proc;
    proc = NULL;
    ui->pushButton_start->setText(idiom.getStart());
    ui->pushButton_folder->setEnabled(true);
    ui->tab_settings->setEnabled(true);
    history += "<font color=red>"+idiom.getStoped()+"</font><br>";
    ui->textBrowser_history->setHtml(history);
  }
}

/**
 * @brief MainWindow::on_pushButton_folder_clicked
 * This methos is a signal used to interface to code the instrucctions to be
 * executed when an user press a FolderButton.  This event will open a folder
 * brower enabling to user to select a folder.
 * Last, the FolderButton the path to the folder selected as a its label.
 */
void MainWindow::on_pushButton_folder_clicked()
{
  QFileDialog dialog;
  dialog.setFileMode(QFileDialog::Directory);
  dialog.setOption(QFileDialog::ShowDirsOnly);
  if (dialog.exec()==1) {
    ui->pushButton_folder->setText( dialog.directory().absolutePath() );
    QDir::setCurrent(dialog.directory().absolutePath());
  }
}

/**
 * @brief MainWindow::on_pushButton_clear_clicked
 * This methos is a signal used to interface to code the instrucctions to be
 * executed when an user press over ClearHistoryButton, then, all information
 * in the history area is cleaned.
 */
void MainWindow::on_pushButton_clear_clicked()
{
    history = "";
    ui->textBrowser_history->setHtml(history);
}

/**
 * @brief MainWindow::on_comboBox_language_currentIndexChanged
 * @param index
 * This methos is a signal used to interface to code the instrucctions to be
 * executed when an user select one of the two languages allowed in the widget.
 * The Interface will change all labels to the corresponding language.
 */
void MainWindow::on_comboBox_language_currentIndexChanged(int index)
{
  idiom.setIdiomType((idiomtype)index);
  refreshIdiom();
}
